package com.cskaoyan.service.wx;

import com.cskaoyan.bean.cart.Cart;
import com.cskaoyan.bean.promotebean.Coupon;
import com.cskaoyan.bean.promotebean.CouponExample;
import com.cskaoyan.bean.promotebean.CouponUser;
import com.cskaoyan.bean.promotebean.CouponUserExample;
import com.cskaoyan.mapper.cart.CartMapper;
import com.cskaoyan.mapper.promotemapper.CouponMapper;
import com.cskaoyan.mapper.promotemapper.CouponUserMapper;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.wx.CheckOut_FlagVo;
import com.cskaoyan.vo.wx.WxCouponMyListVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class WxCouponServiceImpl implements WxCouponService {

    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    CartServiceImpl cartService;

    /**
     * 领取优惠券
     *
     * @param
     * @return
     */
    @Override
    public BaseRespVo receive(Integer couponId, Integer userID) {

        Integer code = userAddCoupon(findTheCoupon(couponId, null), userID);
        //根据领取状态code来返回结果
        return getRespVo(code, "优惠券已经领取过", "优惠券已领完");


    }

    /**
     * 得到所有优惠券
     *
     * @param couponUserExample
     * @param page
     * @param size
     * @return
     */
    @Override
    public WxCouponMyListVo mylist(CouponUserExample couponUserExample, Integer page, Integer size) {
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        ArrayList<Coupon> coupons = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            coupons.add(couponMapper.selectByPrimaryKey(couponUser.getCouponId()));
        }

        //塞入vo
        ArrayList<WxCouponMyListVo.DataBean> data = new ArrayList<>();
        int count = coupons.size();
        //设置pageHelper
        int startIndex = (page - 1) * size;
        int endIndex = (count - startIndex) > size ? (startIndex + size) : (count);


        for (int i = startIndex; i < endIndex; i++) {
            Coupon c = coupons.get(i);
            WxCouponMyListVo.DataBean dataBean = new WxCouponMyListVo.DataBean();
            dataBean.setDesc(c.getDesc()).setDiscount(c.getDiscount().toString()).setEndTime(c.getEndTime())
                    .setId(c.getId()).setMin(c.getMin().toString()).setName(c.getName()).setStartTime(c.getStartTime()
            ).setTag(c.getTag());
            data.add(dataBean);


        }



        return new WxCouponMyListVo(count, data);
    }

    /**
     * 根据优惠券兑换码或者id来查询是否存在此优惠券，若存在返回coupon，不存在返回null
     *
     * @param
     * @return
     */
    @Override
    public Coupon findTheCoupon(Integer couponId, String code) {
        //创建一个example
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();

        //设置一些必要条件，没有删除且处于可用状态
        criteria.andDeletedEqualTo(false);
        criteria.andStatusEqualTo((short) 0);

        if (couponId != null) {
            criteria.andIdEqualTo(couponId);
        }
        if (code != null) {
            criteria.andTypeEqualTo(((short) 2));
            criteria.andCodeEqualTo(code);
        }


        //查询
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        //不存在此优惠券
        if (coupons.size() == 0) {
            return null;
        } else return coupons.get(0);
    }

    @Override
    public BaseRespVo exchange(String code, Integer userId) {
        //先做查询，该优惠券是否存在且处于可领取状态
        Coupon theCoupon = findTheCoupon(null, code);
        //若不存在此优惠券
        if (theCoupon == null) {
            return BaseRespVo.fail742("优惠券不正确");
        }
        //若存在，则调用service层的receive方法
        else {
            int receive = userAddCoupon(theCoupon, userId);
            //根据返回状态来返回vo
            return getRespVo(receive, "优惠券已兑换", "优惠券已领完");
        }

    }

    /**
     * 用户添加优惠券
     *
     * @param coupon
     * @param userId
     * @return
     */
    @Override
    public Integer userAddCoupon(Coupon coupon, Integer userId) {
        //此券是否可领取
        if (coupon.getStatus() == 2) {
            return 7402;
        }
        //查询该用户是否领取该优惠券达到数额限制
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCouponIdEqualTo(coupon.getId());
        //拿到每人限额,查看是否领取达到限额
        Short limit = coupon.getLimit();
        long count = couponUserMapper.countByExample(couponUserExample);
        if (count == limit) {
            return 7401;
        }

        //领取到账户
        CouponUser couponUser = new CouponUser();


        //将相关数据塞入
        couponUser.setUserId(userId);
        couponUser.setCouponId(coupon.getId());
        couponUser.setStartTime(coupon.getStartTime());
        couponUser.setEndTime(coupon.getEndTime());
        couponUser.setStatus((short) 0);
        couponUser.setDeleted(false);
        couponUser.setAddTime(new Date(System.currentTimeMillis()));
        couponUser.setUpdateTime(new Date(System.currentTimeMillis()));
        couponUserMapper.insertSelective(couponUser);

        //更新coupon数量
        Integer total = coupon.getTotal();
        if (total != 0) {

            //如果total不为0，代表数量有限，而表中默认0位无限，故当原本还剩一张被领取之后，改为-1，并且将状态改为2，意为下架
            if (total == 1) {
                coupon.setTotal(-1);
                coupon.setStatus(((short) 2));
            } else if (total > 1) {
                coupon.setTotal(total - 1);
            }
            coupon.setUpdateTime(new Date(System.currentTimeMillis()));
            couponMapper.updateByPrimaryKey(coupon);
        }
        return 0;


    }

    @Override
    public List<Coupon> selectList(Integer id, Integer cartId) {

//        //去购物车里面查询购物车总价
//
//        Cart cart = cartMapper.selectByPrimaryKey(cartId);
//        int price = cart.getPrice().intValue() * (int)cart.getNumber();
//
//        //去couponUser中查询可用的优惠券
//        CouponUserExample couponUserExample = new CouponUserExample();
//        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
//        criteria.andUserIdEqualTo(id);
//        criteria.andDeletedEqualTo(false);
//        criteria.andStatusEqualTo((short)0);
//        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
//
//        //查询满足最低价的优惠券
//        ArrayList<Integer> ids = new ArrayList<>();
//        for (CouponUser couponUser : couponUsers) {
//            ids.add(couponUser.getCouponId());
//        }
//
//        //去查coupon信息
//        CouponExample couponExample = new CouponExample();
//        CouponExample.Criteria criteria1 = couponExample.createCriteria();
//        criteria1.andIdIn(ids);
//        criteria1.andMinGreaterThanOrEqualTo(new BigDecimal(price));
//        List<Coupon> couponList = couponMapper.selectByExample(couponExample);
//
//        return couponList;
        List<Integer> availableCouponIds = getAvailableCouponIds(id, cartId);
        return getAvailableCoupon(availableCouponIds);
    }

    @Override
    public List<Integer> getAvailableCouponIds(Integer userId, Integer cartId) {

        //获取订单总额
        CheckOut_FlagVo totalPriceByUserId = cartService.getTotalPriceByUserId(userId, cartId);
        BigDecimal amount;
        if (totalPriceByUserId == null || totalPriceByUserId.getMessage() != null) {
            return null;
        }


        amount = totalPriceByUserId.getCheckOutVo().getGoodsTotalPrice();


        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false).andStatusEqualTo((short) 0);
        //获取用户所有可用优惠券
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        ArrayList<Integer> integers = new ArrayList<>();
        if (couponUsers.size() == 0) {
            return integers;
        } else {
            for (CouponUser couponUser : couponUsers) {
                if (!integers.contains(couponUser.getCouponId())) {
                    integers.add(couponUser.getCouponId());
                }
            }
            //查询满足满减金额的优惠券
            CouponExample couponExample = new CouponExample();
            couponExample.createCriteria().andMinLessThan(amount).andIdIn(integers);
            List<Coupon> couponList = couponMapper.selectByExample(couponExample);
            ArrayList<Integer> availableCouponIds = new ArrayList<>();
            if (couponList.size() == 0) {
                return availableCouponIds;
            }
            //按照优惠金额大小排序，TreeMap里面是从小到大排序
            TreeMap<BigDecimal, Integer> treeMap = new TreeMap<>();
            for (Coupon coupon : couponList) {
                treeMap.put(coupon.getDiscount(), coupon.getId());
            }
            //得到TreeMap逆排序后的TreeMap，得到其value的合集（这里面是couponId按优惠金额从大到小排序）
            NavigableMap<BigDecimal, Integer> descendingMap = treeMap.descendingMap();
            availableCouponIds.addAll(descendingMap.values());
            return availableCouponIds;
        }


    }

    @Override
    public List<Coupon> getAvailableCoupon(List<Integer> availableCouponIds) {
//        CouponExample couponExample = new CouponExample();
//        couponExample.createCriteria().andIdIn(availableCouponIds);
//        return couponMapper.selectByExample(couponExample);
        //更新了优惠券按优惠金额从大到小排序
        ArrayList<Coupon> coupons = new ArrayList<>();
        for (Integer availableCouponId : availableCouponIds) {
            coupons.add(couponMapper.selectByPrimaryKey(availableCouponId));
        }
        return coupons;
    }

    /**
     * 下架优惠券，并且将用户已领取的优惠券改为下架
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //维护coupon表
        Coupon coupon = new Coupon();
        coupon.setId(id);
//        coupon.setDeleted(true);
        coupon.setStatus((short) 2);
        Date now = new Date(System.currentTimeMillis());
        coupon.setUpdateTime(now);
        couponMapper.updateByPrimaryKeySelective(coupon);

        //维护couponUser表
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.createCriteria().andCouponIdEqualTo(id);
        CouponUser couponUser = new CouponUser();
        couponUser.setUpdateTime(now);
        couponUser.setStatus((short) 2);
        //设置delete=true
//        couponUser.setDeleted(true);
        couponUserMapper.updateByExampleSelective(couponUser,couponUserExample);

    }

    /**
     * 复用一个根据优惠券领取状态来返回响应的Vo
     *
     * @param code
     * @param msg7401
     * @param msg7402
     * @return
     */
    private BaseRespVo getRespVo(int code, String msg7401, String msg7402) {
        if (code == 0) {
            return BaseRespVo.ok();
        } else if (code == 7401) {
            return BaseRespVo.fail740(msg7401);
        } else {
            return BaseRespVo.fail740(msg7402);
        }
    }
}
